package pers.mingshan.thread;

import org.junit.Test;

/**
 * @author hanjuntao
 * @date 2025/9/9 0009
 */
public class SafeThreadStop3 implements Runnable {

    @Override
    public void run() {
       while (true) {
           if (Thread.currentThread().isInterrupted()) {
               System.out.println("当前时间：" + new java.util.Date() + "-线程被中断，退出执行");
               break;
           }

           System.out.println("当前时间：" + new java.util.Date() + "-线程执行中...");
       }

        System.out.println("当前时间：" + new java.util.Date() + "-线程安全退出");
    }

    /**
     * 使用interrupt()方法
     *
     * @throws InterruptedException
     */
    @Test
    public void test2() throws InterruptedException {
        SafeThreadStop3 task = new SafeThreadStop3();
        Thread thread = new Thread(task);
        thread.start();

        // 运行3秒后请求停止
        Thread.sleep(1000);
        thread.interrupt(); // 如果线程在阻塞状态，这会唤醒它

        // 等待线程结束
        thread.join(); // 添加这行代码等待线程结束

        System.out.println("当前时间：" + new java.util.Date() + "-测试方法结束");
    }

}